import os
import socket
import threading

HOST = "0.0.0.0"
PORT = 5678

def handle_client(conn, addr):
    print(f"[连接建立] {addr}")
    try:
        while True:
            data = conn.recv(2048)
            if not data:
                print(f"[连接断开] {addr}")
                break

            msg = data.decode('utf-8', errors='ignore').strip()
            print(f"[接收命令] {msg}")

            # 命令解析
            if msg == "ac_open":
                os.system("ir-ctl -d /dev/lirc0 --send=/root/ac_open.ir")
                reply = "执行空调开机命令成功"
            elif msg == "ac_close":
                os.system("ir-ctl -d /dev/lirc0 --send=/root/ac_close.ir")
                reply = "执行空调关机命令成功"

            else:
                reply = f"未知命令: {msg}"

            conn.sendall(reply.encode('utf-8'))
            print(f"[已发送回复] {reply}")

    except Exception as e:
        print(f"[错误] 处理连接时异常: {e}")
    finally:
        conn.close()


def start_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((HOST, PORT))
    server.listen(5)
    print(f"[服务器启动] 正在监听 {HOST}:{PORT}")

    while True:
        conn, addr = server.accept()
        threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()

if __name__ == "__main__":
    start_server()


